import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.PatternSyntaxException;

public class DataExtractor {

	private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	private static final String DB_URL = "jdbc:mysql://localhost/Miner";
	// "jdbc:mysql://songrecommender.csmwbjcoq6lu.us-east-1.rds.amazonaws.com/song_recommendation";

	static final String USER = "aws";
	static final String PASS = "guhaminer";
	private static ArrayList<Float> means = new ArrayList<Float>();

	public static void main(String[] args) {

		//Extract args
		if (args.length > 0 )
		{
			HypothesisGenerator.pQuantifier = Double.parseDouble(args[0]);
			if (args.length >= 2 )
				HypothesisGenerator.tMinMatch = Integer.parseInt(args[1]);
		}
		
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		String sql = "";
		ArrayList<SongBits> songs = new ArrayList<SongBits>();

		long startTime = System.currentTimeMillis();

		try {
			Class.forName(JDBC_DRIVER);

			conn = DriverManager.getConnection(DB_URL, USER, PASS);

			stmt = conn.createStatement();

			getMeans(conn);

			try {
				SongBits.setMeans(means);

				sql = "SELECT * FROM `Miner`.`Song` WHERE 1";
				rs = stmt.executeQuery(sql);

				SongBits.setMeans(means);

				while (rs.next()) {
					SongBits song = new SongBits(rs);
					songs.add(song);
				}

				rs.close();

			} catch (SQLException se) {
				throw new SQLException("Invalid Query: " + sql);
			}
			conn.close();

			HypothesisGenerator analyzer = formHypotheses();

			analyzer.testHypotheses(songs);

			long endTime = System.currentTimeMillis();
			System.out.printf("Process took: %d ms\n", endTime - startTime);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static HypothesisGenerator formHypotheses() throws Exception{
		// Analyze
		Scanner scanner = null;
		scanner = new Scanner(new File("input.txt"));

		ArrayList<ArrayList<Integer>> allAnte = new ArrayList<ArrayList<Integer>>();
		ArrayList<ArrayList<Integer>> allSucc = new ArrayList<ArrayList<Integer>>();
		
		ArrayList<String> names = new ArrayList<String>( Arrays.asList(HypothesisParameters.columnNames) );
		
		while( scanner.hasNext() )
		{
			
			String[] anteValues = scanner.nextLine().split(" ");
			String[] succValues = scanner.nextLine().split(" ");
	
			ArrayList<Integer> anteTrue = new ArrayList<Integer>();
			ArrayList<Integer> succTrue = new ArrayList<Integer>();
			
			for (int i = 0; i < anteValues.length; i++) {
				String colName = anteValues[i].trim();
				int index = names.indexOf(colName);
				if (index < 0)
					throw new Exception("Invalid input file at: " + colName);
				
				anteTrue.add(index);
						//Integer.parseInt(anteValues[i].trim()));
			}
			for (int i = 0; i < succValues.length; i++) {
				String colName = succValues[i].trim();
				int index = names.indexOf(colName);
				if (index < 0)
					throw new Exception("Invalid input file at: " + colName);
//				
				succTrue.add(index);
			}
			
			allAnte.add(anteTrue);
			allSucc.add(succTrue);
			
			if (scanner.hasNext() )
			{
				//blank line
				scanner.nextLine();
			}
			
		}

		HypothesisGenerator analyzer = new HypothesisGenerator(allAnte, allSucc);
		
		/*OLD version		 
		ArrayList<Integer> empty = new ArrayList<Integer>();
		HypothesisParameters hypothesis = new HypothesisParameters(
				anteTrue, empty, succTrue, empty);
		ArrayList<HypothesisParameters> params = new ArrayList<HypothesisParameters>();
		params.add(hypothesis);

		HypothesisGenerator analyzer = new HypothesisGenerator(params);
		*/
		return analyzer;
	}

	private static void getMeans(Connection conn) {
		Statement stmt = null;
		ResultSet rs = null;
		String sql = "";

		try {
			stmt = conn.createStatement();

			sql = "SELECT AVG(`ArtistFamilarity`) FROM `Miner`.`Song`";
			rs = stmt.executeQuery(sql);
			if (rs.next())
				means.add(rs.getFloat(1));
			sql = "SELECT AVG(`ArtistHotness`) FROM `Miner`.`Song`";
			rs = stmt.executeQuery(sql);
			if (rs.next())
				means.add(rs.getFloat(1));
			sql = "SELECT AVG(`Duration`) FROM `Miner`.`Song`";
			rs = stmt.executeQuery(sql);
			if (rs.next())
				means.add(rs.getFloat(1));
			sql = "SELECT AVG(`Loudness`) FROM `Miner`.`Song`";
			rs = stmt.executeQuery(sql);
			if (rs.next())
				means.add(rs.getFloat(1));
			sql = "SELECT AVG(`SongHotness`) FROM `Miner`.`Song`";
			rs = stmt.executeQuery(sql);
			if (rs.next())
				means.add(rs.getFloat(1));
			sql = "SELECT AVG(`Tempo`) FROM `Miner`.`Song`";
			rs = stmt.executeQuery(sql);
			if (rs.next())
				means.add(rs.getFloat(1));
			sql = "SELECT AVG(`Year`) FROM `Miner`.`Song`";
			rs = stmt.executeQuery(sql);
			if (rs.next())
				means.add(rs.getFloat(1));
		} catch (SQLException e) {

			e.printStackTrace();
		}
	}

}
